package com.imay.live.fragment;


import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.imay.base.fragment.BaseFragment;
import com.imay.live.R;
import com.imay.live.activity.DiscoveryRankingGameListActivity;
import com.imay.live.activity.ProfileActivity;
import com.imay.live.activity.discovery.FollowControl;
import com.imay.live.adapter.GameRankingAdapter;
import com.imay.live.adapter.RankingAdapter;
import com.imay.live.analytics.MobclickAgent;
import com.imay.live.helper.EventHelper;
import com.imay.live.model.RankingGameModel;
import com.imay.live.model.RankingModel;
import com.imay.live.utils.RecyclerViewUtil;
import com.imay.tbas_api.IMYTBASObject;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.util.List;

/**
 * 排行榜
 */
public class RankingFragment extends BaseFragment implements BaseQuickAdapter.OnItemChildClickListener {
    private RecyclerView rcv_ranking;
    private RankingAdapter rankingAdapter;
    private GameRankingAdapter gameRankingAdapter;
    public static final String TYPE_TAG = "type_tag";
    public static final int TYPE_RANKING = 1; //个人入口
    public static final int TYPE_DAYRANKING = 3;
    public static final int TYPE_DISCOVERY_RANKING = 2;
    public static final int TYPE_GAME_RANKING = 4;
    public static final int TYPE_FAMILY = 5;
    private FollowControl followControl;
    private IMYTBASObject followChangeListener;
    private int type;
    private boolean isOwer;

    private HorizontalDividerItemDecoration itemDecoration1;
    private HorizontalDividerItemDecoration itemDecoration2;

    public static RankingFragment newInstance(int type) {
        Bundle args = new Bundle();
        RankingFragment fragment = new RankingFragment();
        args.putInt(TYPE_TAG, type);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_ranking;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        type = getArguments().getInt(TYPE_TAG);
        bindViews();
        if (type == TYPE_RANKING) {
            MobclickAgent.onEvent(getActivity(), "gift_open_get");
        } else if (type == TYPE_GAME_RANKING) {
            List<RankingModel> rankingModelList =
                    getActivity().getIntent().getParcelableArrayListExtra(DiscoveryRankingGameListActivity.MODEL);
            if (rankingModelList != null && !rankingModelList.isEmpty()) {
                setRankingData(rankingModelList);
            }
        }
    }

    private void bindViews() {
        rcv_ranking = $(R.id.rcv_ranking);
        RecyclerViewUtil.setLinearLayoutManager(getActivity(), rcv_ranking);

        if (itemDecoration1 == null) {
            itemDecoration1 = new HorizontalDividerItemDecoration.Builder(getActivity()).colorResId(R.color.bg_f5)
                    .sizeResId(R.dimen.divider_size_1x)
                    .build();
        }

        if (itemDecoration2 == null) {
            itemDecoration2 = new HorizontalDividerItemDecoration.Builder(getActivity()).colorResId(R.color.bg_f5)
                    .sizeResId(R.dimen.divider_size_7x)
                    .build();
        }

    }

    public void setRankingData(List<RankingModel> rankingModelList) {
        if (rcv_ranking == null) {
            bindViews();
        }
        rcv_ranking.removeItemDecoration(itemDecoration1);
        rcv_ranking.removeItemDecoration(itemDecoration2);
        rcv_ranking.addItemDecoration(itemDecoration1);
        if (rankingAdapter == null) {
            rankingAdapter = new RankingAdapter(rankingModelList, type);
            rankingAdapter.setEmptyView(LayoutInflater.from(getActivity()).inflate(R.layout.view_load_layout, null));
            rcv_ranking.setAdapter(rankingAdapter);
            rankingAdapter.setOnItemChildClickListener(this);
            rankingAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    ProfileActivity.start(getActivity(), rankingAdapter.getData().get(position).getUser().getUid());
                }
            });
            registerSocketNotify();
        } else {
            rcv_ranking.setAdapter(rankingAdapter);
            rankingAdapter.setNewData(rankingModelList);
            rankingAdapter.notifyDataSetChanged();
        }
        rcv_ranking.scrollToPosition(0);
    }

    public void setRankingData(List<RankingModel> rankingModelList, View headView) {
        if (rcv_ranking == null) {
            bindViews();
        }
        rcv_ranking.removeItemDecoration(itemDecoration1);
        rcv_ranking.removeItemDecoration(itemDecoration2);
        rcv_ranking.addItemDecoration(itemDecoration1);
        if (rankingAdapter == null) {
            rankingAdapter = new RankingAdapter(rankingModelList, type);
            rankingAdapter.setEmptyView(LayoutInflater.from(getActivity()).inflate(R.layout.view_load_layout, null));
            rankingAdapter.removeAllHeaderView();
            rankingAdapter.addHeaderView(headView);
            rcv_ranking.setAdapter(rankingAdapter);
            rankingAdapter.setOnItemChildClickListener(this);
            rankingAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    ProfileActivity.start(getActivity(), rankingAdapter.getData().get(position).getUser().getUid());
                }
            });
            registerSocketNotify();
        } else {
            rcv_ranking.setAdapter(rankingAdapter);
            rankingAdapter.setNewData(rankingModelList);
            rankingAdapter.notifyDataSetChanged();
        }
        rcv_ranking.scrollToPosition(0);
    }

    public void setRankingData(List<RankingModel> rankingModelList, boolean isOwer) {
        if (rcv_ranking == null) {
            bindViews();
        }
        this.isOwer = isOwer;
        rcv_ranking.removeItemDecoration(itemDecoration1);
        rcv_ranking.removeItemDecoration(itemDecoration2);
        rcv_ranking.addItemDecoration(itemDecoration1);
        if (rankingAdapter == null) {
            rankingAdapter = new RankingAdapter(rankingModelList, type);
            rankingAdapter.setEmptyView(LayoutInflater.from(getActivity()).inflate(R.layout.view_load_layout, null));
            rcv_ranking.setAdapter(rankingAdapter);
            rankingAdapter.setOnItemChildClickListener(this);
            if (!isOwer) {
                rankingAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        ProfileActivity.start(getActivity(), rankingAdapter.getData().get(position).getUser().getUid());
                    }
                });
            }
            registerSocketNotify();
        } else {
            rcv_ranking.setAdapter(rankingAdapter);
            rankingAdapter.setNewData(rankingModelList);
            rankingAdapter.notifyDataSetChanged();
        }
        rcv_ranking.scrollToPosition(0);
    }


    /**
     * @param gameRankingData
     */
    public void setGameRankingData(final List<List<RankingGameModel>> gameRankingData) {
        if (rcv_ranking == null) {
            bindViews();
        }
        rcv_ranking.removeItemDecoration(itemDecoration2);
        rcv_ranking.removeItemDecoration(itemDecoration1);
        rcv_ranking.addItemDecoration(itemDecoration2);
        if (gameRankingAdapter == null) {
            gameRankingAdapter = new GameRankingAdapter(getContext(), gameRankingData);
            gameRankingAdapter.setEmptyView(LayoutInflater.from(getActivity()).inflate(R.layout.view_load_layout, null));
            gameRankingAdapter.setOnItemGameRankClick(new GameRankingAdapter.OnItemGameRankClick() {
                @Override
                public void itemClick(String rankType, String rankTitle) {
                    DiscoveryRankingGameListActivity.start(getActivity(), rankType, rankTitle);
                }

                @Override
                public void personClick(long uid) {
                    ProfileActivity.start(getActivity(), uid);
                }
            });
            rcv_ranking.setAdapter(gameRankingAdapter);
        } else {
            rcv_ranking.setAdapter(gameRankingAdapter);
            gameRankingAdapter.setNewData(gameRankingData);
            gameRankingAdapter.notifyDataSetChanged();
        }
        rcv_ranking.scrollToPosition(0);
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        switch (view.getId()) {
            case R.id.iv_ranking_follow:
                if (followControl == null) {
                    followControl = new FollowControl();
                }
                followControl.followChanged(getActivity().getApplicationContext(), rankingAdapter.getData().get(position).getUser(), false);
                break;
            case R.id.tv_name_ranking:
            case R.id.iv_hear_img_ranking:
                if (!isOwer) {
                    ProfileActivity.start(getActivity(), rankingAdapter.getData().get(position).getUser().getUid());
                }
                break;

        }

    }

    protected void registerSocketNotify() {
        followChangeListener = new IMYTBASObject(false);
        followChangeListener.stringCommand = EventHelper.EVENT_FOLLOW_UICHANGE;
        followChangeListener.setDataResultListener(new IMYTBASObject.OnDataResultListener() {
            @Override
            public void onCommandTaskSuccess(final IMYTBASObject object) {
                refreshFollowStatus(object.stringData);
            }
        });
        followChangeListener.addEventListenWithTBASObject();

    }

    private void refreshFollowStatus(String uidStr) {
        boolean isFollow = true;
        int sp = uidStr.indexOf("#");
        if (sp > 0) {
            uidStr = uidStr.substring(0, sp);
            isFollow = false;
        }
        int uid = Integer.parseInt(uidStr);
        int position = -1;
        if (rankingAdapter != null && rankingAdapter.getData() != null) {
            for (int i = 0; i < rankingAdapter.getData().size(); i++) {
                if (rankingAdapter.getData().get(i).getUser().getUid() == uid) {
                    position = i;
                    rankingAdapter.getData().get(i).getUser().setMyFollow(isFollow);
                    break;
                }
            }
            final int finalPosition = position + rankingAdapter.getHeaderLayoutCount();
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (finalPosition != -1) {
                        rankingAdapter.notifyItemChanged(finalPosition);
                    }
                }
            });
        }


    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (followChangeListener != null) {
            followChangeListener.destroy();
        }
        if (gameRankingAdapter != null) {
            gameRankingAdapter.setOnItemGameRankClick(null);
        }
    }

}
